/**
 * 
 */
package com.gmail.blackdog1987.carcare.service.impl;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gmail.blackdog1987.carcare.dao.CaptchaDao;
import com.gmail.blackdog1987.carcare.dao.GasCouponsDao;
import com.gmail.blackdog1987.carcare.dao.SmsDao;
import com.gmail.blackdog1987.carcare.dao.UserDao;
import com.gmail.blackdog1987.carcare.entity.TCaptcha;
import com.gmail.blackdog1987.carcare.entity.TGasCoupons;
import com.gmail.blackdog1987.carcare.entity.TSms;
import com.gmail.blackdog1987.carcare.entity.TUser;
import com.gmail.blackdog1987.carcare.service.UserService;
import com.gmail.blackdog1987.carcare.util.ErrorCode;

/**
 * 
 * @author 董国超
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private SmsDao smsDao;
	@Autowired
	private CaptchaDao captchaDao;
	@Autowired
	private GasCouponsDao gasCouponsDao;
	private static final String GET_CODE_STR = " 验证码有效期30分钟，请及时使用";
//	private ScoreService scoreService;
	
//	static Logger log = Logger.getLogger(UserServiceImpl.class);
	
	public Map<String, Object> doLogin(Map<String, String> filter) {
		Map<String, Object> result = new HashMap<String, Object>();
		
		result.put("code", ErrorCode.NO);
		
		String username = filter.get("username");
		String pwd = filter.get("pwd");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("username", username);
		param.put("pwd", pwd);
		List<TUser> users = userDao.find(param);
		if(users==null||users.size()==0){ // 用户名或密码错误
			result.put("code", ErrorCode.LOGIN_PWD);
		}else{
			result.put("result", users.get(0));
		}
		return result;
	}

	@Override
	public Map<String, Object> doRegister(Map<String, String> filter) {
		Map<String, Object> result = new HashMap<String, Object>();
		
		result.put("code", ErrorCode.NO);
		
		String username = filter.get("username");
		String pwd = filter.get("pwd");
		String code = filter.get("code");
		String cartype = filter.get("cartype");
		String carnumber = filter.get("carnumber");
		String enginenumber = filter.get("enginenumber");
		String carbonenumber = filter.get("carbonenumber");
//		String baoyang = filter.get("baoyang");
//		String nianjian = filter.get("nianjian");
		
		
		List<TUser> users = userDao.findBy("username", username);
		if(users!=null&&users.size()!=0){ 
			result.put("code", ErrorCode.REG_EXISTS);
			return result;
		}
		if(StringUtils.isBlank(code)){
			result.put("code", ErrorCode.REG_CODE);
			return result;
		}
		// 校验验证码
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("receiver", username);
		params.put("captcha", code);
		params.put("status", 1);
		params.put("deadline>=", new Date());
		Map<String, String> sort = new HashMap<String, String>();
		sort.put("deadline", "desc");
		List<TCaptcha> captchas = captchaDao.find(params, sort);
		if(captchas.isEmpty() || !captchas.get(0).getCaptcha().equals(code)){
			result.put("code", ErrorCode.REG_CODE);
			return result;
		}
		for (TCaptcha tCaptcha : captchas) {
			tCaptcha.setType(0);
		}
		captchaDao.saveAll(captchas);
		
		TUser user = new TUser();
		user.setUsername(username);
		user.setPwd(pwd);
		user.setCartype(cartype);
		user.setCarnumber(carnumber);
		user.setEnginenumber(enginenumber);
		user.setCarbonenumber(carbonenumber);
		Serializable userid = userDao.create(user);
		user.setId(Integer.valueOf(userid.toString()));
		
		// 判断是否完成了所有资料的填写，完成了就创建电子卷并且下发
		if (cartype != null && cartype.length() != 0 && carnumber != null
				&& carnumber.length() != 0 && enginenumber != null
				&& enginenumber.length() != 0 && carbonenumber != null
				&& carbonenumber.length() != 0) {
			TGasCoupons coupons = new TGasCoupons();
			coupons.setCode(System.currentTimeMillis()+"");
			Calendar c =  Calendar.getInstance();
			coupons.setCreatetime(new Date());
			coupons.setStarttime(new Date());
			c.add(Calendar.YEAR, 1);
			coupons.setEndtime(new Date(c.getTime().getTime()));
			coupons.setStatus(0);
			coupons.setUserid(user.getId());
			gasCouponsDao.save(coupons);
			
			// 发短信
			TSms sms = new TSms();
			sms.setContent("欢迎您注册车拉丁，送您一张洗车卷 ： " + coupons.getCode() + " （一年内有效）");
			sms.setCreatetime(new Date());
			sms.setFailuretimes(0);
			sms.setPhone(username);
			sms.setUpdatetime(new Date());
			sms.setStatus(0);
			smsDao.save(sms);
		}
		
		result.put("result", user);
		return result;
	}

	@Override
	public Map<String, Object> doEditInfo(Map<String, String> filter) {
		Map<String, Object> result = new HashMap<String, Object>();
		
		result.put("code", ErrorCode.NO);
		
		return result;
	}

	public Map<String, Object> doGetCode(Map<String, String> filter) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", ErrorCode.NO);
		String mobile = filter.get("mobile");
		if(!StringUtils.isBlank(mobile)&&mobile.matches("^1\\d{10}$")){
			TCaptcha code = new TCaptcha();
			code.setType(1);
			Calendar date = Calendar.getInstance();
			date.add(Calendar.MINUTE, 30);
			code.setDeadline(date.getTime());
			code.setReceiver(mobile);
			code.setStatus(1);
			String randomNumber = String.valueOf(getRandomNumber6());
			code.setCaptcha(randomNumber);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("status", 1);
			map.put("receiver", mobile);
			List<TCaptcha> oldCode = captchaDao.find(map);
			for (TCaptcha object : oldCode) {
				object.setStatus(0);
			}
			// 老数据全部无效
			captchaDao.saveAll(oldCode);
			captchaDao.create(code);
			
			// add sms
			TSms sms = new TSms();
			sms.setContent(randomNumber + GET_CODE_STR);
			sms.setCreatetime(new Date());
			sms.setFailuretimes(0);
			sms.setPhone(mobile);
			sms.setStatus(0);
			sms.setUpdatetime(new Date());
			smsDao.create(sms);
		}
		return result;
	}
	
	/**
	 * 生成随机6位数字
	 * @return
	 */
	private int getRandomNumber6(){
		int[] array = {0,1,2,3,4,5,6,7,8,9};
		Random rand = new Random();
		for (int i = 10; i > 1; i--) {
		    int index = rand.nextInt(i);
		    int tmp = array[index];
		    array[index] = array[i - 1];
		    array[i - 1] = tmp;
		}
		int randomCode = 0;
		for(int i = 0; i < 6; i++)
			randomCode = randomCode * 10 + array[i];
		return randomCode;
	}
}
